<template>
  <view class="app-container">
    
    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-row">
        <view class="search-item">
          <input 
            class="input" 
            v-model="queryParams.remarks" 
            placeholder="请输入名称搜索" 
            @confirm="handleQuery"
          />
        </view>
        <view class="search-item">
          <button class="btn-search" @click="handleQuery">搜索</button>
        </view>
        <view class="search-item">
          <button class="btn-add" @click="handleAdd">新增</button>
        </view>
      </view>
    </view>

    <!-- 工具栏 -->
    <view class="toolbar" style="display: none;">
      <button class="btn btn-primary" @click="handleAdd">
        <text class="icon">+</text>
        <text>新增</text>
      </button>
    </view>

         <!-- 密码列表 -->
     <view class="list-container">
      <view 
        v-for="(item, index) in passwordList" 
        :key="item.id" 
        class="list-item"
      >
        <uni-swipe-action>
          <uni-swipe-action-item 
            :right-options="swipeOptions" 
            @click="handleSwipeClick($event, item)"
          >
            <view class="item-content-wrapper" @click="handleItemClick(item)">
              <view class="item-header">
                <view class="item-title">{{item.remarks}}</view>
                <view class="item-project">{{item.classificationName || '未分类'}}</view>
              </view>
              
              <view class="item-content">
                <view class="info-row">
                  <text class="info-label">账号：</text>
                  <text class="info-value">{{item.username}}</text>
                  <button class="btn-copy" @click.stop="copyText(item.username)">复制</button>
                </view>
                
                <view class="info-row">
                  <text class="info-label">密码：</text>
                  <text class="info-value">{{item.password}}</text>
                  <button class="btn-copy" @click.stop="copyText(item.password)">复制</button>
                </view>
                
                <view class="info-row">
                  <text class="info-label">网址：</text>
                  <text class="info-value">{{item.website}}</text>
                  <button class="btn-copy" @click.stop="copyText(item.website)">复制</button>
                </view>
              </view>
            </view>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
      
      
      
             <!-- 无数据提示 -->
       <view class="empty-state" v-if="!loading && passwordList.length === 0">
         <image class="empty-image" src="/static/images/empty-data.png" mode="aspectFit"></image>
         <view class="empty-text">暂无密码数据</view>
       </view>
     </view>

    <!-- 新增/修改弹窗 -->
    <uni-popup ref="popup" type="center" :mask-click="false">
      <view class="dialog-container">
        <view class="dialog-header">
          <text class="dialog-title">{{title}}</text>
          <text class="dialog-close" @click="cancel">×</text>
        </view>
        
        <scroll-view class="dialog-content" scroll-y>
          <view class="form-container">
            <view class="form-row">
              <view class="form-item">
                <text class="form-label">名称</text>
                <input class="form-input" v-model="form.remarks" placeholder="请输入名称" />
              </view>
            </view>
            
            <view class="form-row">
              <view class="form-item">
                <text class="form-label">账号</text>
                <input class="form-input" v-model="form.username" placeholder="请输入账号" />
              </view>
              <view class="form-item">
                <text class="form-label">密码</text>
                <input class="form-input" v-model="form.password" type="password" placeholder="请输入密码" />
              </view>
            </view>
            
            <view class="form-row">
              <view class="form-item">
                <text class="form-label">网址</text>
                <input class="form-input" v-model="form.website" placeholder="请输入网址" />
              </view>
            </view>
            
            <view class="form-row">
              <view class="form-item full-width">
                <text class="form-label">备注</text>
                <textarea class="form-textarea" v-model="form.remark" placeholder="请输入备注信息" />
              </view>
            </view>
          </view>
        </scroll-view>
        
        <view class="dialog-footer">
          <button class="btn btn-default" @click="cancel">取消</button>
          <button class="btn btn-primary" @click="submitForm">确定</button>
        </view>
      </view>
    </uni-popup>

    <!-- 详情弹窗 -->
    <uni-popup ref="detailPopup" type="center" :mask-click="true">
      <view class="detail-container">
        <view class="detail-header">
          <text class="detail-title">{{detailItem.remarks}}</text>
          <text class="detail-close" @click="closeDetail">×</text>
        </view>
        
        <view class="detail-content">
          <view class="detail-section">
            <view class="detail-item">
              <view class="detail-info">
                <text class="detail-label">账号</text>
                <text class="detail-value">{{detailItem.username}}</text>
              </view>
            </view>
            
            <view class="detail-item">
              <view class="detail-info">
                <text class="detail-label">密码</text>
                <text class="detail-value">{{detailItem.password}}</text>
              </view>
            </view>
            
            <view class="detail-item">
              <view class="detail-info">
                <text class="detail-label">网址</text>
                <text class="detail-value">{{detailItem.website}}</text>
              </view>
            </view>
            
            <view class="detail-item">
              <view class="detail-info">
                <text class="detail-label">项目</text>
                <text class="detail-value">{{detailItem.classificationName || '未分类'}}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="detail-footer">
          <button class="detail-btn detail-btn-copy" @click="copyAllInfo">一键复制所有</button>
          <button class="detail-btn detail-btn-primary" @click="closeDetail">关闭</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { listPassword, getPassword, addPassword, delPassword, updatePassword } from '../../api/password';

export default {
  // 页面配置
  onPullDownRefresh: true,
  data() {
    return {
      loading: true,
      ids: [],
      hasSelection: false,

      passwordList: [],
      currentProject: {},
      title: '',
      popupShow: false,
                           queryParams: {
          pageNum: 1,
          pageSize: 100000,
          remarks: '',
          classificationId: ''
        },
      form: {},
      rules: {
        remarks: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      },

      
      swipeOptions: [
        {
          text: '修改',
          style: {
            backgroundColor: '#007aff'
          }
        },
        {
          text: '删除',
          style: {
            backgroundColor: '#ff3b30'
          }
        }
      ],
      detailItem: {}
    };
  },
  onLoad() {
    this.getGlobalProject();
    this.getList();
  },

  onPullDownRefresh() {
    // 下拉刷新
    this.onRefresh();
  },
  methods: {
    // 获取全局项目
    getGlobalProject() {
      // 从本地存储获取
      const storedProject = uni.getStorageSync('currentProject');
      if (storedProject && storedProject.id) {
        this.currentProject = storedProject;
        // 如果不是"全部"选项，则设置项目分类ID
        if (storedProject.id !== 'all') {
          this.queryParams.classificationId = storedProject.id;
          this.form.classificationId = storedProject.id;
        }
      }
      
      // 从全局数据获取
      if (getApp().globalData && getApp().globalData.currentProject) {
        this.currentProject = getApp().globalData.currentProject;
        // 如果不是"全部"选项，则设置项目分类ID
        if (getApp().globalData.currentProject.id !== 'all') {
          this.queryParams.classificationId = getApp().globalData.currentProject.id;
          this.form.classificationId = getApp().globalData.currentProject.id;
        }
      }
      
      // 如果没有选择项目，返回首页
      if (!this.currentProject.id) {
        uni.showModal({
          title: '提示',
          content: '请先选择项目分类',
          showCancel: false,
          success: () => {
            uni.navigateBack();
          }
        });
      }
    },
    
         getList() {
       this.loading = true;
       
       return listPassword(this.queryParams).then(res => {
         if (res.code === 200) {
           // 直接替换数据，一次性加载所有
           this.passwordList = res.rows || [];
           
                     // 调试信息
          console.log('密码列表信息:', {
            currentLength: this.passwordList.length,
            rows: res.rows?.length || 0
          });
         }
         this.loading = false;
         return res;
       }).catch((error) => {
         console.error('获取密码列表失败:', error);
         this.loading = false;
         throw error;
       });
     },
    
         handleQuery() {
       // 重置查询参数
       this.passwordList = [];
       this.getList();
     },
    
                 resetQuery() {
        this.queryParams = {
          pageNum: 1,
          pageSize: 100000,
          remarks: '',
          classificationId: this.currentProject.id !== 'all' ? this.currentProject.id : ''
        };
        this.passwordList = [];
        this.getList();
      },
    
    handleSelectionChange(e) {
      this.ids = e.detail.value.map(item => item.id);
      this.hasSelection = this.ids.length > 0;
    },
    
    handleAdd() {
      this.resetForm();
      this.title = '添加密码';
      this.$refs.popup.open();
    },
    
    handleUpdate(row) {
      getPassword(row.id).then(res => {
        if (res.code === 200) {
          this.form = res.data;
          this.title = '修改密码';
          this.$refs.popup.open();
        }
      });
    },
    
    handleDelete(row) {
      const ids = row ? [row.id] : this.ids;
      uni.showModal({
        title: '提示',
        content: `是否确认删除选中的${ids.length}条数据？`,
        success: res => {
          if (res.confirm) {
            delPassword(ids).then(() => {
              uni.showToast({ title: '删除成功', icon: 'success' });
              this.getList();
              this.ids = [];
              this.hasSelection = false;
            });
          }
        }
      });
    },
    
    copyText(text) {
      uni.setClipboardData({
        data: text,
        success: () => {
          uni.showToast({ title: '复制成功', icon: 'success' });
        }
      });
    },
    
    submitForm() {
      // 简单的表单验证
      if (!this.form.remarks) {
        uni.showToast({ title: '请输入名称', icon: 'none' });
        return;
      }
      if (!this.form.username) {
        uni.showToast({ title: '请输入账号', icon: 'none' });
        return;
      }
      if (!this.form.password) {
        uni.showToast({ title: '请输入密码', icon: 'none' });
        return;
      }

      // 设置项目分类ID - 必须选择一个具体项目
      if (!this.currentProject.id || this.currentProject.id === 'all') {
        uni.showToast({
          title: '请先选择一个具体的项目分类',
          icon: 'none'
        });
        return;
      }

      this.form.classificationId = this.currentProject.id;

      if (this.form.id) {
        updatePassword(this.form).then(() => {
          uni.showToast({ title: '修改成功', icon: 'success' });
          this.$refs.popup.close();
          this.getList();
        });
      } else {
        addPassword(this.form).then(() => {
          uni.showToast({ title: '新增成功', icon: 'success' });
          this.$refs.popup.close();
          this.getList();
        });
      }
    },
    
    cancel() {
      this.$refs.popup.close();
    },
    
    resetForm() {
      this.form = {
        id: null,
        remarks: '',
        username: '',
        password: '',
        website: '',
        classificationId: this.currentProject.id !== 'all' ? this.currentProject.id : '',
        remark: ''
      };
    },
    
    
    
         onRefresh() {
      // 重置查询参数
      this.passwordList = [];
      
      // 重新获取所有数据
      this.getList().then(() => {
        // 数据加载完成后停止下拉刷新动画
        uni.stopPullDownRefresh();
      }).catch(() => {
        // 即使出错也要停止下拉刷新动画
        uni.stopPullDownRefresh();
      });
    },
    
    handleItemClick(item) {
      this.showDetail(item);
    },
    
    showDetail(item) {
      this.detailItem = item;
      this.$refs.detailPopup.open();
    },
    
    closeDetail() {
      this.$refs.detailPopup.close();
    },
    
    copyAllInfo() {
      const allInfo = `名称：${this.detailItem.remarks}
账号：${this.detailItem.username}
密码：${this.detailItem.password}
网址：${this.detailItem.website}
项目：${this.detailItem.classificationName || '未分类'}`;
      
      uni.setClipboardData({
        data: allInfo,
        success: () => {
          uni.showToast({ title: '所有信息已复制', icon: 'success' });
        }
      });
    },
    
    handleSwipeClick(event, item) {
      if (event.index === 0) { // 修改
        this.handleUpdate(item);
      } else if (event.index === 1) { // 删除
        this.handleDelete(item);
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 搜索区域 */
.search-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 0;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.search-row {
  display: flex;
  align-items: center;
  background-color: #f8f9fa;
  border: 2rpx solid #e9ecef;
  border-radius: 16rpx;
}

.search-item {
  display: flex;
  align-items: center;
  flex: 1;
  border-right: 1rpx solid #e9ecef;
}

.search-item:last-child {
  flex: none;
  width: auto;
  border-right: none;
}

.search-item:nth-child(1) {
  flex: 1;
  min-width: 200rpx;
}

.search-item:nth-child(2),
.search-item:nth-child(3) {
  flex: none;
  width: 100rpx;
}

.input {
  flex: 1;
  height: 70rpx;
  background-color: transparent;
  border: none;
  border-radius: 0;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  transition: all 0.3s ease;
}

.input:focus {
  background-color: #fff;
}

.btn-search {
  height: 70rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  line-height: 70rpx;
  border-radius: 0;
  border: none;
  background-color: #007aff;
  color: #fff;
  font-weight: 500;
  white-space: nowrap;
}

.btn-search:active {
  background-color: #0056cc;
}

.btn-add {
  height: 70rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  line-height: 70rpx;
  border-radius: 0;
  border: none;
  background-color: #4cd964;
  color: #fff;
  font-weight: 500;
  white-space: nowrap;
}

.btn-add:active {
  background-color: #3aa34f;
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 30rpx;
  font-size: 28rpx;
  line-height: 70rpx;
  border-radius: 12rpx;
  border: none;
  font-weight: 500;
  min-width: 120rpx;
}

.btn-primary {
  background-color: #007aff;
  color: #fff;
}

.btn-primary:active {
  background-color: #0056cc;
}

.btn-danger {
  background-color: #ff3b30;
  color: #fff;
}

.btn-danger:active {
  background-color: #cc2e25;
}

.btn-danger:disabled {
  background-color: #ccc;
  color: #999;
}

.btn-export {
  background-color: #4cd964;
  color: #fff;
}

.btn-export:active {
  background-color: #3aa34f;
}

.icon {
  margin-right: 8rpx;
  font-size: 28rpx;
}

/* 列表容器 */
.list-container {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  margin-bottom: 20rpx;
  flex: 1;
}





/* 无数据状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 30rpx;
  text-align: center;
  min-height: 400rpx;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.8;
}

.empty-text {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 20rpx;
  font-weight: 500;
}

.empty-tip {
  font-size: 28rpx;
  color: #999;
  line-height: 1.5;
}

/* 左滑操作样式 */
.item-content-wrapper {
  background-color: #fff;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: all 0.3s ease;
}

.item-content-wrapper:active {
  background-color: #f8f9fa;
}

.list-item {
  padding: 0;
  border-bottom: none;
}

.list-item:last-child .item-content-wrapper {
  border-bottom: none;
}

.list-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: all 0.3s ease;
}

.list-item:last-child {
  border-bottom: none;
}

.list-item:active {
  background-color: #f8f9fa;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.item-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
  flex: 1;
  margin-right: 20rpx;
}

.item-project {
  font-size: 24rpx;
  color: #666;
  background-color: #f0f0f0;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  white-space: nowrap;
}

.item-content {
  margin-bottom: 20rpx;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
  flex-wrap: wrap;
}

.info-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 15rpx;
  white-space: nowrap;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  margin-right: 15rpx;
  word-break: break-all;
}

.btn-copy {
  font-size: 24rpx;
  color: #007aff;
  background: none;
  border: none;
  padding: 5rpx 10rpx;
  border-radius: 8rpx;
  white-space: nowrap;
}

.btn-copy:active {
  background-color: #f0f8ff;
}

/* 弹窗 */
.dialog-container {
  width: 90vw;
  max-width: 800rpx;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #f8f9fa;
  border-bottom: 1rpx solid #e9ecef;
}

.dialog-title {
  flex: 1;
  text-align: center;
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
}

.dialog-close {
  font-size: 48rpx;
  color: #999;
  padding: 0 20rpx;
  line-height: 100rpx;
}

.dialog-close:active {
  color: #666;
}

.dialog-content {
  max-height: 60vh;
  padding: 30rpx;
}

.form-container {
  /* 表单容器样式 */
}

.form-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 25rpx;
  gap: 20rpx;
}

.form-item {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.form-item.full-width {
  flex: none;
  width: 100%;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  font-weight: 500;
}

.form-input {
  height: 70rpx;
  background-color: #f8f9fa;
  border: 2rpx solid #e9ecef;
  border-radius: 12rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  transition: all 0.3s ease;
}

.form-input:focus {
  border-color: #007aff;
  background-color: #fff;
}

.form-textarea {
  width: 100%;
  height: 150rpx;
  background-color: #f8f9fa;
  border: 2rpx solid #e9ecef;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  resize: none;
}

.form-textarea:focus {
  border-color: #007aff;
  background-color: #fff;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  padding: 30rpx;
  gap: 30rpx;
  border-top: 1rpx solid #e9ecef;
  background-color: #f8f9fa;
}

.dialog-footer .btn {
  min-width: 160rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 30rpx;
  font-weight: 500;
}

.btn-default {
  background-color: #f8f9fa;
  color: #666;
  border: 2rpx solid #e9ecef;
}

.btn-default:active {
  background-color: #e9ecef;
}

/* 详情弹窗样式 */
.detail-container {
  width: 90vw;
  max-width: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.detail-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  flex: 1;
  text-align: center;
}

.detail-close {
  font-size: 48rpx;
  color: #999;
  padding: 0 20rpx;
  line-height: 100rpx;
}

.detail-close:active {
  color: #666;
}

.detail-content {
  width: 100%;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.detail-section {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx dashed #eee;
}

.detail-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.detail-label {
  font-size: 28rpx;
  color: #666;
  white-space: nowrap;
  min-width: 120rpx;
}

.detail-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  word-break: break-all;
}

.detail-footer {
  width: 100%;
  display: flex;
  justify-content: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #e9ecef;
}

.detail-btn {
  min-width: 160rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 30rpx;
  font-weight: 500;
  border-radius: 12rpx;
  border: none;
}

.detail-btn-copy {
  background-color: #4cd964;
  color: #fff;
  margin-right: 20rpx;
}

.detail-btn-copy:active {
  background-color: #3aa34f;
}

.detail-btn-primary {
  background-color: #007aff;
  color: #fff;
}

.detail-btn-primary:active {
  background-color: #0056cc;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .search-row {
    flex-direction: column;
    align-items: stretch;
    gap: 15rpx;
  }
  
  .search-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  
  .search-item:last-child {
    width: 100%;
  }
  
  .btn-search {
    width: 100%;
  }
  
  .toolbar {
    flex-wrap: wrap;
    gap: 15rpx;
  }
  
  .btn {
    min-width: 100rpx;
    padding: 0 20rpx;
  }
  
  .form-row {
    flex-direction: column;
    gap: 15rpx;
  }
  
  .form-item {
    margin-right: 0;
  }
}
</style>
